<?php

namespace app\controller\teacher;

use app\BaseController;
use app\model\Chapter;
use app\model\Course;
use app\model\Media;
use app\model\StudentMedia;
use app\model\VStudentCourse;
use Error;
use Exception;
use \think\facade\Db;

/**
 * 章节媒体控制器
 */
class TeacherChapterMedia extends BaseController
{
    /**
     * 章节、媒体列表
     */
    public function list()
    {
        $courseID = $this->request->param('courseID');
        if (empty(Course::where("TID", $this->user['TID'])->find($courseID))) {
            return resultError('无权限');
        }
        $chapter = Db::name('chapter')
            ->where(['courseID' => $courseID])
            ->select()->toArray();
        $chapterID = array_column($chapter, 'chapterID');
        $joinTable = Db::name('studentmedia')->field(['MID','count(*) as number'])->group('MID')->buildSql();;
        $media = Db::name('media')->field(['media.MID','TID','basicName','credit','storgeLocation','type','chapterID','number'])->where('chapterID', 'in', $chapterID)->leftJoin([$joinTable=>'t1'],'media.mid=t1.mid')->select();
        $data = [];
        foreach ($chapter as $cp) {
            $data[$cp['chapterID']] = $cp;
            $data[$cp['chapterID']]['media'] = [];
        }
        foreach ($media as $md) {
            $data[$md['chapterID']]['media'][] = $md;
        }
        return resultSuccess(array_values($data));
    }

    /**
     * 添加章节
     */
    public function addChapter()
    {

        if ($this->request->isPost()) {
            $courseID = $this->request->param('courseID');
            if (empty(Course::where("TID", $this->user['TID'])->find($courseID))) {
                return resultError('无权限');
            }
            $chapter = new Chapter;
            if ($chapter->save(
                [
                    'title' => $this->request->param('title'),
                    'courseID' => $this->request->param('courseID'),
                    'TID' => $this->user['TID']
                ]
            )) {
                return resultSuccess();
            } else {
                return resultError();
            }
        } else {
            return resultError();
        }
    }

    /**
     * 删除章节
     */
    public function deleteChapter()
    {
        if ($this->request->isGet()) {
            $chapter = Chapter::find($this->request->param('chapterID'));
            if ($chapter->TID != $this->user['TID']) {
                return resultError('无权限');
            }
            if ($chapter->delete()) {
                return resultSuccess();
            } else {
                return resultError();
            }
        } else {
            return resultError();
        }
    }

    /**
     * 修改章节
     */
    public function editChapter()
    {
        if ($this->request->isPost()) {
            $chapter = Chapter::find($this->request->param('chapterID'));
            if ($chapter->TID != $this->user['TID']) {
                return resultError('无权限');
            }
            $chapter->title = $this->request->param('title');
            if ($chapter->save()) {
                return resultSuccess();
            } else {
                return resultError();
            }
        } else {
            return resultError();
        }
    }

    /**
     * 添加媒体
     */
    public function addMedia()
    {
        $chapter = Chapter::find($this->request->param('chapterID'));
        if ($this->request->param('credit') == null) {
            return resultError('参数不全');
        }
        if ($chapter == null) {
            return resultError('无此章节');
        }
        if ($chapter->TID != $this->user['TID']) {
            return resultError('无权限');
        }
        //鉴权
        $uploadData = $this->upload();
        if ($uploadData['isComplete'] == true) {
            $media = new Media;
            $media->TID = $this->user['TID'];
            $media->chapterID = $chapter->chapterID;
            $media->basicName = $uploadData['title'];
            $media->storgeLocation = $uploadData['filepath'];
            $media->type = $uploadData['ext'];
            $media->credit = $this->request->param('credit');
            if ($media->save() == true) {
                return resultSuccess();
            } else {
                @unlink($uploadData['filepath']);
                return resultError('失败');
            }
        }
        return resultSuccess($uploadData);
    }

    public function editMedia()
    {
        if ($this->request->param('credit') == null) {
            return resultError('参数不全');
        }
        $media = Media::where(['TID' => $this->user['TID'], 'MID' => $this->request->param('MID')])->find();
        if ($media == null) {
            return resultError('无权限');
        }
        //鉴权
        $media->basicName = $this->request->param('title');
        $media->credit = $this->request->param('credit');
        if ($media->save() == true) {
            return resultSuccess();
        } 
        return resultError();
    }

    /**
     * 删除媒体
     */
    public function deleteMedia()
    {
        if ($this->request->param('MID') == null) return resultError('无此媒体');
        $media = Media::find($this->request->param('MID'));
        if (Chapter::where(['TID' => $this->user['TID'], 'chapterID' => $media->chapterID])->find() == null) {
            return resultError('无权限');
        }
        try {
            //echo config('filesystem.disks.public.mediaRoot') .$media->storgeLocation;
            unlink(config('filesystem.disks.public.mediaRoot') . $media->storgeLocation);
        } catch (Exception $e) {
            //echo $e;
            return resultError('文件删除失败');
        }
        if ($media->delete()) {
            return resultSuccess('删除成功');
        }
        return resultError('删除失败');
    }

    /**
     * 统计未完成
     */
    public function countMedia(){
        $MID = $this->request->param('MID');
        $media = Media::where(['TID' => $this->user['TID'], 'MID' => $MID])->find();
        if ($media == null) {
            return resultError('无权限');
        }
        $chapter =Chapter::where(['TID' => $this->user['TID'], 'chapterID' => $media->chapterID])->find();
        $unFinishStudentList = VStudentCourse::field(['SID', 'studentName', 'claseName'])->where('courseID',$chapter->courseID)
            ->where('SID','not in', function($query) use($MID){$query->table('studentmedia')->field('SID')->where('MID', $MID);})
            ->select();
        //var_dump(VStudentCourse::getLastSql());
        return resultSuccess($unFinishStudentList);
    }
}
